<template>
  <BasicModal
    v-bind="$attrs"
    title="添加用户"
    width="80%"
    :close-fun="closeFun"
    @register="registerModal"
    @ok="handleSubmit"
    destroyOnClose
  >
    <div class="flex">
      <DeptTree class="w-1/4 xl:w-1/5" style="border: 1px solid #efefef" @select="handleSelect" />
      <BasicTable class="w-3/4 xl:w-4/5" @register="registerTable" />
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTable, useTable } from '@/components/Table';

  import DeptTree from '../user/dept-tree.vue';

  import { getUserPageApi } from '@/api/system/user';
  import type { SystemUserItem } from '@/api/system/model/userModel';

  const emit = defineEmits(['success', 'register']);
  let deptId: string | undefined = undefined;
  const selection = ref<SystemUserItem[]>([]);
  let cacheSelectedRows: SystemUserItem[] = [];
  const [registerTable, { setSelectedRowKeys, reload, getSelectRowKeys }] = useTable({
    rowKey: 'id',
    title: '',
    api: getUserPageApi,
    beforeFetch: async (params) => {
      return { ...params, deptId };
    },
    rowSelection: {
      onChange: (_selectedRowKeys, selectedRows) => {
        selection.value = selectedRows as SystemUserItem[];
      },
      onSelect: (record: SystemUserItem, selected: boolean) => {
        if (selected) {
          cacheSelectedRows.push(record);
        } else {
          cacheSelectedRows = cacheSelectedRows.filter((item) => item.id !== record.id);
        }
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        if (selected) {
          selectedRows.forEach((item) => {
            const index = cacheSelectedRows.findIndex((cacheItem) => cacheItem.id === item.id);
            if (index === -1) {
              cacheSelectedRows.push(item);
            }
          });
        } else {
          cacheSelectedRows = cacheSelectedRows.filter(
            (cacheItem) => !changeRows.find((item) => item.id === cacheItem.id),
          );
        }
      },
    },
    columns: [
      {
        title: '用户名',
        dataIndex: 'username',
        // width: 180,
      },
      {
        title: '部门',
        dataIndex: 'deptName',
        // width: 180,
      },
    ],
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
  });
  const [registerModal, { closeModal }] = useModalInner((data) => {
    const { users = [] } = data || {};
    if (Array.isArray(users)) {
      cacheSelectedRows = users;
      setSelectedRowKeys(users.map((user) => user.id));
    }
  });

  const handleSelect = async (id: string) => {
    deptId = id;
    // 刷新前保留上一次的rowkey
    const selectRowKeys = getSelectRowKeys();
    await reload();
    setSelectedRowKeys(selectRowKeys);
  };

  const closeFun = () => {
    setSelectedRowKeys([]);
    deptId = undefined;
    cacheSelectedRows = [];
    return true;
  };
  async function handleSubmit() {
    emit('success', cacheSelectedRows);
    closeModal();
    closeFun();
  }
</script>

<style lang="less"></style>
